//
//  tcm_registeredViewController.swift
//  TCM_TradingProject
//
//  Created by 吕春海 on 2018/8/15.
//  Copyright © 2018年 lvchunhai. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Toaster
import TextFieldEffects

enum pageType {
    case pageTypeRegister
    case pageTypeForget
}

class tcm_registeredViewController: TCM_BaseViewController {
    
    var timer: Timer!
    var leftTime: Int = 60
    var codeStr: String?
    var phoneStr: String?
    var passwordStr: String?
    var isShowPassword: Bool!
    let disposeBag = DisposeBag()
    var pageShowType = pageType.pageTypeRegister

    @IBOutlet weak var phoneTF: AkiraTextField!
    @IBOutlet weak var codeTF: AkiraTextField!
    @IBOutlet weak var pwdTF: AkiraTextField!
    @IBOutlet weak var phoneImageView: UIImageView!
    @IBOutlet weak var getCodeButton: UIButton!
    @IBOutlet weak var showPwdButton: UIButton!
    @IBOutlet weak var registeredButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()


        initialUI()

    }
    
    func initialUI() {
        registeredButton.layer.cornerRadius = 4
        registeredButton.clipsToBounds = true
        
        getCodeButton.layer.borderColor = TCM_HexRGB(0x744735).cgColor;
        getCodeButton.layer.borderWidth = 1;
        getCodeButton.layer.cornerRadius = 2;
        getCodeButton.clipsToBounds = true
        
        isShowPassword = false
        
        textFieldInput()
        buttonClick()
        
        switch pageShowType {
        case .pageTypeRegister:
            self.title = "注册"
            self.registeredButton.setTitle("立即注册", for: .normal)
            self.pwdTF.placeholder = "密码"
        case .pageTypeForget:
            self.title = "忘记密码"
            self.registeredButton.setTitle("完成", for: .normal)
            self.pwdTF.placeholder = "设置新密码"
        }
    }
    func textFieldInput() {
        phoneTF.rx.text.orEmpty.asObservable()
            .subscribe(onNext: { [weak self] in
                
                self?.changeplaceholderFont(textField: (self?.phoneTF)!)
                
                self?.phoneStr = $0
                if  (self?.phoneStr?.count)! >= 11 {
                    self?.phoneImageView.image = UIImage(named: "TCM_LoginAccountOK")
                    self?.phoneTF.textMaxLength = 11
                    
                } else {
                    self?.phoneImageView.image = UIImage(named: "")
                    
                }
                self?.showButton()
            })
            .disposed(by: disposeBag)
        
        codeTF.rx.text.orEmpty.changed
            .subscribe(onNext: { [weak self] in
                self?.codeStr = $0
                
                if (self?.codeStr?.count)! >= 6 {
                    self?.codeTF.textMaxLength = 6
                } else {
                    self?.showPwdButton.isHidden = true
                }
                self?.showButton()
            })
            .disposed(by: disposeBag)
        
        pwdTF.rx.text.orEmpty.changed
            .subscribe(onNext: { [weak self] in
                self?.passwordStr = $0
                self?.showButton()
                if (self?.passwordStr?.count)! > 0 {
                    self?.showPwdButton.isHidden = false

                } else {
                    self?.showPwdButton.isHidden = true
                }
                
                if  (self?.passwordStr?.count)! >= 16 {
                    self?.pwdTF.textMaxLength = 16
                    Toast(text: "密码最多16位").show()
                }
            })
            .disposed(by: disposeBag)
    }
    
    //注册按钮现实逻辑
    func showButton() {
        if  (self.pwdTF.text?.count)! >= 6 && (self.phoneTF.text?.count)! >= 11 && (self.codeTF.text?.count)! >= 6 {
            self.registeredButton.isEnabled = true
            self.registeredButton.alpha = 1
        } else {
            self.registeredButton.isEnabled = false
            self.registeredButton.alpha = 0.4
        }
    }
    
    func buttonClick() {
        //注册按钮
        registeredButton.rx.tap
            .bind{ [weak self] in
                self?.phoneTF.resignFirstResponder()
                self?.codeTF.resignFirstResponder()
                self?.pwdTF.resignFirstResponder()
                if (self?.pwdTF.text?.isPassword(minNumber: 6, maxNumber: 16))! {
                    switch (self?.pageShowType)! {
                    case .pageTypeRegister:
                         Toast(text: "注册成功").show()
                    case .pageTypeForget:
                         Toast(text: "修改成功").show()
                    }
                } else {
                    Toast(text: "密码应为6-16位的数字与字母的组合").show()
                }
            }
            .disposed(by: disposeBag)
        
        
        
        //密文明文切换
        showPwdButton.rx.tap
            .bind{ [weak self] in
                if self?.isShowPassword == false {
                    self?.showPwdButton.setImage(UIImage(named: "TCM_LoginPwdShow"), for: .normal)
                    self?.pwdTF.isSecureTextEntry = false
                    self?.isShowPassword = true
                } else {
                    self?.showPwdButton.setImage(UIImage(named:"TCM_LoginPwdHidden"), for: .normal)
                    self?.pwdTF.isSecureTextEntry = true
                    self?.isShowPassword = false
                }
                
            }
            .disposed(by: disposeBag)
        
        //发送验证码发送点击事件
        getCodeButton.rx.tap
            .bind{ [weak self] in
                self?.phoneTF.resignFirstResponder()
                
                if (self?.phoneTF.text?.isMobilePhoneNumber())! {
                    self?.requestCode()
                } else {
                    Toast(text: "手机号格式不正确").show()
                }
                
            }
            .disposed(by: disposeBag)
    }

    // MARK: -请求
    //获取验证码
    func requestCode() {
//        let param = [
//            "account": self.accountTF.text!,
//            "flag": 2
//            ] as [String : Any]
//
//        let headers = ["user-agent" : "iOS"]
//
//        Alamofire.request("http://192.168.10.93:30111/api/account/sendSms", method: .post, parameters: param, encoding: URLEncoding.default, headers: headers).responseJSON { (responseJson) in
//
//            switch responseJson.result {
//            case .success(let data):
//                let dataDic = data as! Dictionary<String, Any>
//                let code = dataDic["code"] as! Int
//
//                let message = dataDic["message"] as! String
//
//                if code == 200 {
//                    print(dataDic)
//                    self.startCountDown()
//                } else {
//                    Toast(text: message).show()
//                }
//
//            case .failure( _):
//                Toast(text: "网络状况不佳，请重试").show()
//            }
//        }
        self.startCountDown()
    }
    
    //开始倒计时
    func startCountDown() {
        leftTime = 60
        getCodeButton.setTitle("\(leftTime)s", for: .disabled)
        getCodeButton.isEnabled = false
        //获取该计时器的剩余时间
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(tickDown), userInfo: nil, repeats: true)
    }
    
    @objc func tickDown() {
        //将剩余时间减少1秒
        
        leftTime -= 1
        //修改UIDatePicker的剩余时间
        getCodeButton.setTitle("\(leftTime)s", for: .disabled)
        //如果剩余时间小于等于0
        if leftTime <= 0 {
            cancelTimer(buttonText: "重新获取")
        }
    }
    
    //取消定时器
    func cancelTimer(buttonText: String) {
        timer?.invalidate()
        getCodeButton.isEnabled = true
        getCodeButton.setTitle(buttonText, for: .normal)
    }
    
    //修改输入/非输入的placeholder字体大小
    func changeplaceholderFont(textField: AkiraTextField) {
        if textField.isFirstResponder || (textField.text?.isEmpty)! == false {
            textField.placeholderFontScale = 0.875
        } else {
            textField.placeholderFontScale = 1
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
